package com.fare.taluo.application.impl.analyse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fare.taluo.application.analyse.AirCompanyTrendContrastCabinApplication;
import com.fare.taluo.application.fetl.SinglePlaneInfoApplication;
import com.fare.taluo.core.domain.config.channel.SourceEntity;
import com.fare.taluo.core.domain.config.city.PortEntity;
import com.fare.taluo.core.domain.config.line.FlightInfoEntity;
import com.fare.taluo.fetl.domain.entity.SinglePlaneInfoEntity;
import com.fare.taluo.fusionCharts.FusionChartsTemplateModel;
import com.fare.taluo.fusionCharts.SimpleFusionChartsBuilder;
import com.fare.taluo.util.FusionChartsUtil_2;
import com.fare.taluo.util.I18nUtil;
import com.fare.taluo.util.flightInfo.SameChannelContrastUtil;
import com.fare.taluo.vo.core.PlaneInfo;
import com.fare.taluo.vo.report.SameChannelContrastVO;
import com.fare.taluo.vo.report.SpreadVo;
import com.fare.taluo.vo.report.XmlVO;
@Transactional
@Service("airCompanyTrendContrastCabinApplication")
public class AirCompanyTrendContrastCabinApplicationImpl implements
		AirCompanyTrendContrastCabinApplication {
	@Resource(name = "singlePlaneInfoApplication")
	private SinglePlaneInfoApplication singlePlaneInfoApplication;
	//SinglePlaneInfoApplicationImpl application =new	SinglePlaneInfoApplicationImpl();
	
	@Override
	public String getFusionChartsXMLStr(String fromCityCode, String toCityCode,
			String flightStartDate, String flightEndDate,
			String[] carrierFlightnoCabin, String dataSourceHbaseKey, String priceType,Locale locale)
			throws Exception {
		 PortEntity pe=new PortEntity();
		 PortEntity fromPort = pe.findByPortCode(fromCityCode);//出发城市实体
		 PortEntity toPort = pe.findByPortCode(toCityCode);//到达城市实体
		 //航班日期list
		 List<String> flightDate=FusionChartsUtil_2.getDatesStr(flightStartDate, flightEndDate);
		 Map<String,PlaneInfo> map =  new  HashMap<String,PlaneInfo>();
		
		 //渠道_起点(使用三字码)_终点(使用三字码)_航班号_航班日期(年月日时) 00001CANNKG00ZH96772013021307
		 														//	20000PEKSZX00CZ32562013073108
		 FusionChartsTemplateModel model=FusionChartsTemplateModel.getNewDefaultInstance();//报表模型
		 model.addChartAttr(FusionChartsTemplateModel.AN_Caption, fromPort.getCityName()+"-"+toPort.getCityName()+" 航空公司航班走势对比");
		 model.addCategroyLabels(FusionChartsUtil_2.getDatesStrFormatMMdd(flightDate));
		 long dataSetId=1000L;
		 SourceEntity source=new SourceEntity();
		 for(String cfc:carrierFlightnoCabin){//用户所选择的
			 if(StringUtils.isNotEmpty(cfc)){
				 String channelKey;
				 String carrierKey = cfc.split("_")[0].trim();
				 String flightNo = cfc.split("_")[1];
				 String cabinType = cfc.split("_")[2];
				 if(dataSourceHbaseKey==null || "".equals(dataSourceHbaseKey.trim())){//数据来源为官网，需要逐一匹对
					 SourceEntity company= source.findByCarrierKey(carrierKey).get(0);
					 channelKey=company.getHbaseKey();
				 }else{//数据来源为渠道
					 channelKey=dataSourceHbaseKey;
				 }
				 List<PlaneInfo> infos = new ArrayList<PlaneInfo>();
				 SinglePlaneInfoEntity entity =new SinglePlaneInfoEntity();
				 /*for(String fd:flightDate){
					 List<SinglePlaneInfoEntity> listEntity = entity.findPlaneInfoByCondition(channelKey,carrierKey, fromCityCode, toCityCode, fd, flightNo);
					 if(com.fare.taluo.util.StringUtils.checkList(listEntity)){
						 SinglePlaneInfoEntity singlePlane = listEntity.get(0);
						 PlaneInfo p = SameChannelContrastUtil.conver2Planeinfo(singlePlane,cabinType,priceType);
						 infos.add(p);
					 }else{
						 infos.add(null);
					 }
					 
				 }*/
			
				 
				 List<SinglePlaneInfoEntity> listEntity = entity.findPlaneInfoPropertyAll(channelKey,carrierKey, fromCityCode, toCityCode, null, flightNo);
				 if ("lowest".equalsIgnoreCase(priceType)) {
					 listEntity = SameChannelContrastUtil.getLowestByLineEachDay(listEntity, flightDate);
					} else if ("highest".equalsIgnoreCase(priceType)) {
						//否则找到最高价
						listEntity = SameChannelContrastUtil.getHighestByLineEachDay(listEntity, flightDate);
					}
				 if(com.fare.taluo.util.StringUtils.checkList(listEntity)){
					 for (SinglePlaneInfoEntity singlePlane : listEntity) {
						 PlaneInfo p = SameChannelContrastUtil.conver2Planeinfo(singlePlane,cabinType,priceType);
						 infos.add(p);
					}
					
				 }else{
					 infos.add(null);
				 }
				 //找出单个渠道价差表格
				 map = SameChannelContrastUtil.getSingleSpreadForm(flightDate,infos,map);
				 
				 List<String> prices=//开始提取数值
						 FusionChartsUtil_2.getPriceValueCabin(infos,locale);
				 String setsStr=FusionChartsUtil_2.generateDashedByFormat(prices,locale);//完整的Set字符串
				 //构建模型
				 model.createDataSet(dataSetId);
				 model.addDataSetAttr(dataSetId,FusionChartsTemplateModel.AN_Seriesname, flightNo);
				 model.addSetFullStrIntoDataSet(dataSetId, setsStr);
				 model.addDataSetAttr(dataSetId, FusionChartsTemplateModel.AN_RenderAs, "Line");//以折现展示数据
				 dataSetId++;
			 }
			 
		 }
		 model.addStyleToObject("ToolTip", FusionChartsTemplateModel.STYLE_ToolTip_FontSize_15);//全局style
		 model.addStyleToObject("Caption", FusionChartsTemplateModel.STYLE_Caption_FontSize_15);//全局style,标题15
		 String xml=SimpleFusionChartsBuilder.getInstance().buildXMLStr(model);
		 //获得价差表格list
			List<SameChannelContrastVO> spreadVos =  getSpreadListForm(flightDate,map, carrierFlightnoCabin,locale);
			XmlVO xmlvo = new XmlVO();
			xmlvo.setXmlString(xml);
			StringBuffer resultBuffer = new StringBuffer();
			String jsonStr = com.fare.taluo.util.JsonUtil.toJson(spreadVos);
			resultBuffer.append("{\"Total\":"+spreadVos.size()+","+ "\"Rows\":"+jsonStr+","+ "\"Xml\":"+com.fare.taluo.util.JsonUtil.toJson(xmlvo)+"}");	
			String json = resultBuffer.toString();
		    return json;		
	}
	
private List<SameChannelContrastVO> getSpreadListForm(List<String> flightDate,Map<String,PlaneInfo> map,String[] carrierFlightnoCabins,Locale locale){
		
		List<SameChannelContrastVO> vos = new ArrayList<SameChannelContrastVO>();
		for (String date : flightDate) {
			int i = 0;
			SameChannelContrastVO vo = new SameChannelContrastVO();
			for (String carrierFlightnoCabin : carrierFlightnoCabins) {
				String carrierName = carrierFlightnoCabin.split("_")[3].trim();
				if(null!=I18nUtil.getProperties(locale).get(carrierName)){
					carrierName=I18nUtil.getProperties(locale).get(carrierName);
				}
				//设置本航
				if(i == 0){
					PlaneInfo p = map.get(carrierFlightnoCabin.split("_")[0].trim()+"_"+date)==null?null:map.get(carrierFlightnoCabin.split("_")[0].trim()+"_"+date);
					if(null != p){
						vo.setNativeCarrier(carrierName);
						vo.setDate(date);
						
						vo.setNativePrice(p.getCabins().size()>0?""+p.getCabins().get(0).getPrice():null);
					}else{
						vo.setDate(date);
						vo.setNativeCarrier(carrierName);
						vo.setNativePrice(null);
					}
					
				}else{
					//获得非本航的其它航
					PlaneInfo p = map.get(carrierFlightnoCabin.split("_")[0].trim()+"_"+date)==null?null:map.get(carrierFlightnoCabin.split("_")[0].trim()+"_"+date);
					SpreadVo svo = new SpreadVo();
					
					if(null != p){
						Double price = p.getCabins().size()>0?p.getCabins().get(0).getPrice():0.0;
						svo.setCarrierName(carrierName);
						if(vo.getNativePrice()==null || price == 0.0){
							svo.setSpread(null);
							svo.setSpreadAmount(null);
							svo.setPrice(null);
						}else{
							svo.setSpreadAmount(""+(price-Double.parseDouble(vo.getNativePrice())));
							svo.setSpread(SameChannelContrastUtil.getSpreadToString(""+price,vo.getNativePrice()));
							svo.setPrice(""+price);
						}
						
					}else{
						svo.setCarrierName(carrierName);
						svo.setSpread(null);
						svo.setSpreadAmount(null);
						svo.setPrice(null);
					}
					vo.getContrastList().add(svo);
				}
				i++;
			}
			vos.add(vo);
		}
		return vos;
	}
	

	
/*	private CabinEntityVO convert2Vo(CabinVO cabinVO){
		CabinEntityVO vo = new CabinEntityVO();
		vo.setCabinType(cabinVO.getCabinType());
		vo.setPrice(cabinVO.getPrice());
		return vo;
		
	}*/
	
	

}
